//
//  XGL_FansPageViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/24.
//

import UIKit
import MJRefresh

class XGL_FansPageViewController: UIViewController,CustomNavgationBar {
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var searchItem: SearchItemView!
    var tableView: UITableView!
    var datasource: [FollowAndFansuserData] = []
    var showDatas: [FollowAndFansuserData] = []
    let header = MJRefreshNormalHeader()
    let footer = MJRefreshBackNormalFooter()
    var pageIndex: NSInteger = 1

    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "")
        self.hudView.backgroundColor = .clear
        self.hudView.hudView.backgroundColor = .clear
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        self.getFollowerDataRequest()
    }
    


}

extension XGL_FansPageViewController{
    @objc private func refresh(){
        self.pageIndex = 1
        self.getFollowerDataRequest()
    }
    @objc private func getMore(){
        self.getFollowerDataRequest()
    }
    @objc private func removeItemAction(sender: UIButton){
        let index = sender.tag - 3000
        let data = self.showDatas[index]
        sender.isSelected = !sender.isSelected
        self.followRequest(id: data.id, index: index,asFollow: data.following == 0)
    }
}

extension XGL_FansPageViewController{
    private func getFollowerDataRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<FollowAndFansuserData>>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .Fans(page: self.pageIndex, size: 20))) { result in
            switch result{
            case .success(let response):
                self.hudView.dismiss()
                if let model = response.resultData{
                    if self.header.isRefreshing{
                        self.datasource = model.data
                        self.header.endRefreshing()
                        self.footer.resetNoMoreData()
                    }else if self.footer.isRefreshing{
                        self.datasource.append(contentsOf: model.data)
                        self.footer.endRefreshing()
                    }else{
                        self.datasource = model.data
                    }
                    if model.totalPages <= model.currentPage{
                        self.footer.endRefreshingWithNoMoreData()
                    }
                    self.showDatas = self.datasource
                    self.tableView.reloadData()
                }
                break
            default:
                self.hudView.dismiss()
                break
            }
        }
    }
    
    private func followRequest(id: String,index: NSInteger,asFollow: Bool){
        self.hudView.backgroundColor = .clear
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .Follow(userId: id, isFollow: asFollow))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                self.header.beginRefreshing()
                break
            default:
                break
            }
        }
    }
}

extension XGL_FansPageViewController: UISearchBarDelegate{
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.searchItem.pickupSearchBar()
        self.searchItem.searchBar.text = ""
        self.showDatas = self.datasource
        self.tableView.reloadData()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let searchKey = searchBar.text {
            self.searchItem.searchBar.resignFirstResponder()
            self.showDatas = self.datasource.filter({ data in
                return data.nickname.contains(searchKey)
            })
            self.tableView.reloadData()
        }
    }
}

extension XGL_FansPageViewController: UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.showDatas.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 104.0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: XGL_FansTableViewCell.self)
        cell.itemData = self.showDatas[indexPath.row]
        cell.unfollowItem.tag = indexPath.row + 3000
        cell.unfollowItem.addTarget(self, action: #selector(self.removeItemAction(sender:)), for: .touchUpInside)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.showDatas[indexPath.row]
        let vc = XGL_userDataViewController(userId: model.id) {
            self.showDatas.remove(at: indexPath.row)
            self.tableView.reloadData()
        }
        self.navigationController?.pushViewController(vc)
    }
}

extension XGL_FansPageViewController{
    private func createXglView(){
        let titleText = UILabel().then { make in
            make.text = "Followers"
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Semibold(fontSize: 32.0)
        }
        self.tableView = UITableView().then({ make in
            make.register(cellWithClass: XGL_FansTableViewCell.self)
            make.dataSource = self
            make.delegate = self
            make.separatorStyle = .none
            make.backgroundColor = .clear
        })
        header.setTitle("Pull down refresh", for: .idle)
        header.setTitle("Release update", for: .pulling)
        header.setTitle("Refresh...", for: .refreshing)
        header.setRefreshingTarget(self, refreshingAction: #selector(self.refresh))
        tableView.mj_header = header
        footer.setTitle("No more data", for: .noMoreData)
        footer.setRefreshingTarget(self, refreshingAction: #selector(self.getMore))
        tableView.mj_footer = footer
        self.view.addSubviews([titleText,tableView])
        titleText.snp.makeConstraints { make in
            make.left.equalTo(15.0)
            make.top.equalTo(PanNavibarH + 15.0)
        }
        self.tableView.snp.makeConstraints { make in
            make.width.centerX.equalToSuperview()
            make.bottom.equalTo(-BottomHeight)
            make.top.equalTo(titleText.snp.bottom).offset(10.0)
        }
    }
    
    func creatClearNavigationBar(title: String) {
        self.navigationController?.navigationBar.barStyle = .default
        setNeedsStatusBarAppearanceUpdate()
        let backColor = UIColor.clear
        let imageIcon = imageWithName("icon_xgl_back_white")
       
        let navView = UIView().then { make in
            make.backgroundColor = backColor
        }
        let backItem = MXCustomButton().then { make in
            make.setImage(imageIcon, for: .normal)
            make.buttonSelectAction { [weak self] in
                guard let `self` = self else { return }
                self.backAction()
            }
        }
        let titleView = UILabel().then { make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Regular(fontSize: 18.0)
            make.text = title
        }
        self.searchItem = SearchItemView().then { make in
            make.searchBar.delegate = self
        }
        navView.addSubview(backItem)
        navView.addSubview(titleView)
        navView.addSubview(self.searchItem)
        self.view.addSubview(navView)
        backItem.snp.makeConstraints { make in
            make.left.equalTo(5.0)
            make.width.height.equalTo(50.0)
            make.bottom.equalTo(-3.0)
        }
        titleView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backItem)
        }
        self.searchItem.snp.makeConstraints { make in
            make.centerY.equalTo(backItem)
            make.right.equalTo(-12.0)
            make.height.equalTo(40.0)
            make.width.equalTo(40.0)
        }
        navView.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(PanNavibarH)
        }
    }
}
